package com.hlyue.ingress.consecutiveportalhacking;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import org.joda.time.DurationFieldType;
import org.joda.time.Seconds;

/**
 * Created by v-linyhe on 8/28/2015.
 */
public class NotificationUtils {
    public static void doSendNotification(final Context context) {
        Notification n = new Notification.Builder(context)
                .setContentTitle(ConsecutiveHackingUtils.getConsecutiveDays(context) + " days consecutive hacking")
                .setContentText(formatTimeString(ConsecutiveHackingUtils.getPendingTime(context)) + " before timeout")
                .addAction(android.R.drawable.ic_menu_add, "hack",
                        PendingIntent.getBroadcast(context, 0, new Intent(ACTION_HACK).setPackage(context.getPackageName()),
                                PendingIntent.FLAG_UPDATE_CURRENT))
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .build();
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify("hacking", 1, n);
    }

    private final static String ACTION_HACK = "ACTION_HACK";
    private static BroadcastReceiver mHackedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConsecutiveHackingUtils.doHacking(context);
            doSendNotification(context);
        }
    };

    public static void registerReceivers(final Context context) {
        context.registerReceiver(mHackedReceiver, new IntentFilter(ACTION_HACK));
    }
    public static void unRegisterReceivers(final Context context) {
        context.unregisterReceiver(mHackedReceiver);
    }

    public static String formatTimeString(final Seconds seconds) {
        final StringBuilder builder = new StringBuilder();
        if (seconds.get(DurationFieldType.hours()) != 0) {
            builder.append(seconds.get(DurationFieldType.hours())).append("hour");
        }
        if (seconds.get(DurationFieldType.minutes()) != 0) {
            builder.append(seconds.get(DurationFieldType.minutes())).append("minute");
        }
        return builder.toString();
    }

}
